﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace DAXT
{
    public partial class FormListADUsers : Form
    {
        public FormListADUsers()
        {
            InitializeComponent();
        }

        private void buttonListUsers_Click(object sender, EventArgs e)
        {
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, textBoxDomain.Text))
                {
                    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                    {
                        foreach (var result in searcher.FindAll())
                        {
                            if (result.DistinguishedName.IndexOf("OU=AxDevelopment") > -1 ||
                                result.DistinguishedName.IndexOf("OU=AxConsulting") > -1)
                            {
                                DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;

                                listBoxUsers.Items.Add(textBoxDomain.Text + "\\" + de.Properties["samAccountName"].Value);
                                textBoxUsers.Text += textBoxDomain.Text + "\\" + de.Properties["samAccountName"].Value + ";";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        private void ListADUsers_Load(object sender, EventArgs e)
        {

        }
    }
}
